<?php

namespace app\admin\controller;

use think\facade\Db;
use app\common\model\User;

class AuthGroup extends Base
{

    protected $tb = "auth_group";

    /**
     * 查看
     */
    public function index()
    {
        $authGroupData = Db::name($this->tb)->order('id desc')->paginate(10);
        return view('admin/group', [
            'tb' => $this->tb,
            'authGroupData' => $authGroupData,
        ]);
    }

    /**
     * 新增
     */
    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $res = Db::name($this->tb)->insert($data);
            if ($res) {
                return alert('操作成功', 'index', 6);
            } else {
                return alert('操作失败', 'index', 5);
            }
        }
        return view('admin/group_add');
    }

    /**
     * 编辑
     */
    public function edit()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $res = Db::name($this->tb)->update($data);
            if ($res) {
                return alert('操作成功', 'index', 6);
            } else {
                return alert('操作失败', 'index', 5);
            }
        }
        $id = input('id');
        $authGroupData = Db::name($this->tb)->where(['id'=>$id])->find();
        return view('admin/group_edit',[
            'authGroupData' => $authGroupData
        ]);
    }

    /**
     * 分配权限
     */
    public function power()
    {
      
        if (request()->isPost()){
            $data = input('post.');
            $data['rules'] = implode(',',$data['rules']);
            $res = Db::name("auth_group")->update($data);
            if ($res) {
                return alert('操作成功', 'index', 6);
            } else {
                return alert('操作失败', 'index', 5);
            }
        }
        $id = input('id');
        $authRuleData = Db::name("auth_rule")->where("parent_id",0)->where('status',1)->select()->toArray();
        $authGroupData = Db::name($this->tb)->where(['id'=>$id])->find();
        foreach ($authRuleData as $k=>$v){
            $authRuleData[$k]['children'] = Db::name('auth_rule')->where('parent_id',$v['id'])->where('status',1)->select()->toArray();
        }
        $rulesArr = explode(',',$authGroupData['rules']);
        return view('admin/group_power',[
            'authGroupData' => $authGroupData,
            'authRuleData' => $authRuleData,
            'rulesArr' => $rulesArr,
        ]);
    }

}
